package plugin;
  
import javax.servlet.FilterChain;   
import javax.servlet.ServletException;   
import javax.servlet.ServletRequest;   
import javax.servlet.ServletResponse;   
import javax.servlet.http.HttpServletResponse;   
import javax.servlet.http.HttpServletResponseWrapper;   
import javax.servlet.http.HttpServletRequest;   
import java.io.IOException;   

import javax.servlet.*; 
/**  
 * Removes jsessionid from encoded URLs, see http://jira.jboss.com/jira/browse/JBSEAM-3018  
 *  
 * More details: http://foreverprecio.us/groovy_tech  
 *  
 * @author Christian Bauer  
 */  
@SuppressWarnings("deprecation")  
public class DisableUrlSessionFilter implements Filter {   
	
	public void init(FilterConfig config) throws ServletException {}
	
	
	public void destroy() {}
	
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)   
            throws IOException, ServletException {   
  
        if (!(req instanceof HttpServletRequest)) {   
            chain.doFilter(req, res);   
            return;   
        }   
  
        HttpServletRequest request = (HttpServletRequest) req;   
        HttpServletResponse response = (HttpServletResponse) res;   
  
        // Redirect requests with JSESSIONID in URL to clean version (old links bookmarked/stored by bots)   
        // This is ONLY triggered if the request did not also contain a JSESSIONID cookie! Which should be fine for bots...   
        
  
        // Prevent rendering of JSESSIONID in URLs for all outgoing links   
        HttpServletResponseWrapper wrappedResponse =   
            new HttpServletResponseWrapper(response) {   
                @Override  
                public String encodeRedirectUrl(String url) {   
                    return url;   
                }   
  
                @Override  
                public String encodeRedirectURL(String url) {   
                    return url;   
                }   
  
                @Override  
                public String encodeUrl(String url) {   
                    return url;   
                }   
  
                @Override  
                public String encodeURL(String url) {   
                    return url;   
                }   
            };   
            
            String url = request.getRequestURL().toString();
            int i = url.indexOf(";jsessionid=");
            int len = url.length();
            if (i >0){
               url = request.getRequestURL().delete(i, len).toString();

               if (request.getQueryString() != null)
            	   url +="?"+request.getQueryString();   

               response.sendRedirect(url);
               return;
            }
            
        chain.doFilter(req, wrappedResponse);   
  
    }   
}  
